package com.ugoodtech.mdcc.core.service.impl;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.dto.ComplaintKPIResponse;
import com.ugoodtech.mdcc.core.dto.ComplaintSearch;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.service.ComplaintKPIService;
import com.ugoodtech.mdcc.core.service.ComplaintSearchService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class ComplaintKPIServiceImpl implements ComplaintKPIService {

    @Autowired
    private ComplaintSearchService complaintSearchService;

    @Autowired
    private ComplaintReportRepository complaintReportRepository;

    @Autowired
    private ComplaintReportDataRepository complaintReportDataRepository;

    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;

    @Autowired
    private ComplaintReportLogRepository complaintReportLogRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private ComplaintUserRepository complaintUserRepository;

    //第一张表统计
    private double totalTime = 0.0;
    private Integer completeCount = 0;
    private Integer notCompleteCount = 0;
    private Integer stopCount = 0;
    private Integer timeOut = 0;

    //第二张统计表
    private Map<String, String[]> reportProvinceMap;

    //第三张表
    private Map<String, Integer> reportBrandMap;
    private Map<String, Integer> reportOtherBrandMap;

    //第五张表
    private Integer reasonableCount = 0;
    private Integer leaderFollowConut = 0;

    //第六张表
    private Map<String, Integer> reportSolutionMap;

    //第七张表
    private boolean isUser;
    private Map<Long, String[]> reportUserNameMap;

    /**
     * 统计投诉报告
     *
     * @param complaintSearch
     * @param clientUser
     * @return
     */
    @Override
    public Object statComplaint(ComplaintSearch complaintSearch, User clientUser) {
        isUser = false;
        if (StringUtils.isNotEmpty(complaintSearch.getUserName())) {
            isUser = true;
        }
        ComplaintKPIResponse complaintKPIResponse = new ComplaintKPIResponse();
        //第一张表统计
        totalTime = 0.0;
        completeCount = 0;
        notCompleteCount = 0;
        stopCount = 0;
        timeOut = 0;
        //第二张统计表
        reportProvinceMap = new HashMap<>();
        //第三张表
        reportBrandMap = new HashMap<>();
        reportOtherBrandMap = new HashMap<>();
        //第五张表
        reasonableCount = 0;
        leaderFollowConut = 0;
        //第六张表
        reportSolutionMap = new HashMap<>();
        //第七张表
        reportUserNameMap = new HashMap<>();

        List<Long> complaintIds = complaintSearchService.searchComplaintReport(complaintSearch, clientUser);
        if (complaintIds.isEmpty()){
            return complaintKPIResponse;
        }
        Map<Long, Integer> reportIdMap = new HashMap<>();
        for (Long id : complaintIds) {
            reportIdMap.put(id, 1);
        }

        for (Map.Entry<Long, Integer> complaintId : reportIdMap.entrySet()) {
            ComplaintReport complaintReport = complaintReportRepository.findOne(complaintId.getKey());
            if (null != complaintReport) {
                //统计第一张表
                reportStatusMap(complaintReport);
                //统计第二张表
                reportProvinceMap(complaintReport);
                //统计第三张表
                reportBrandMap(complaintReport);
                //统计第五张表
                reportUserMap(complaintReport);
                //统计第六张表
                reportSolutionMap(complaintReport);
            }
        }
        //统计第七张表
        if (isUser) {
            reportUserNameMap(new ArrayList<>(reportIdMap.keySet()), complaintSearch.getUserName());
        }
        //统计第一张表
        List<String[]> table1List = new ArrayList<>();
        String[] table1 = new String[6];
        table1[0] = String.valueOf(reportIdMap.size());
        table1[1] = getDecimalDouble(totalTime);
        table1[2] = String.valueOf(completeCount);
        table1[3] = String.valueOf(notCompleteCount);
        table1[4] = String.valueOf(stopCount);
        table1[5] = String.valueOf(timeOut);
        table1List.add(table1);
        complaintKPIResponse.setTable1(table1List);

        //统计第二张表
        List<String[]> reportProvinceTime = new ArrayList<>();
        for (Map.Entry<String, String[]> entry : reportProvinceMap.entrySet()) {
            String[] reportProvinceArray = new String[3];
            reportProvinceArray[0] = entry.getKey();
            reportProvinceArray[1] = entry.getValue()[0];
            reportProvinceArray[2] = entry.getValue()[1];
            reportProvinceTime.add(reportProvinceArray);
        }
        complaintKPIResponse.setTable2(reportProvinceTime);

        //统计第三张表
        List<String[]> table3 = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : reportBrandMap.entrySet()) {
            String[] values = new String[2];
            values[0] = entry.getKey();
            values[1] = entry.getValue().toString();
            table3.add(values);
        }
        complaintKPIResponse.setTable3(table3);
        List<String[]> otherBrand = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : reportOtherBrandMap.entrySet()) {
            String[] values = new String[2];
            values[0] = entry.getKey();
            values[1] = entry.getValue().toString();
            otherBrand.add(values);
        }
        complaintKPIResponse.setOtherBrand(otherBrand);


        //统计第四张表
        List<String[]> table4 = new ArrayList<>();
        String[] table = new String[2];
        table[0] = "已完成";
        table[1] = String.valueOf(completeCount);
        table4.add(table);
        table = new String[2];
        table[0] = "未完成";
        table[1] = String.valueOf(notCompleteCount);
        table4.add(table);
        table = new String[2];
        table[0] = "中断";
        table[1] = String.valueOf(stopCount);
        table4.add(table);
        complaintKPIResponse.setTable4(table4);

        //统计第五张表
        List<String[]> table5 = new ArrayList<>();
        table = new String[2];
        table[0] = "合理时间内跟进数量";
        table[1] = String.valueOf(reasonableCount);
        table5.add(table);
        table = new String[2];
        table[0] = "需大区经理处理数量";
        table[1] = String.valueOf(leaderFollowConut);
        table5.add(table);
        complaintKPIResponse.setTable5(table5);

        //统计第六张表
        List<String[]> table6 = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : reportSolutionMap.entrySet()) {
            table = new String[2];
            table[0] = entry.getKey();
            table[1] = entry.getValue().toString();
            table6.add(table);
        }
        complaintKPIResponse.setTable6(table6);

        //统计第七张表
        List<String[]> table7 = new ArrayList<>();
        if (!reportUserNameMap.isEmpty()) {
            for (Map.Entry<Long, String[]> entry : reportUserNameMap.entrySet()) {
                table7.add(entry.getValue());
            }
            complaintKPIResponse.setTable7(table7);
        }
        return complaintKPIResponse;
    }


    /**
     * 统计第一张表
     *
     * @param complaintReport
     */
    private void reportStatusMap(ComplaintReport complaintReport) {
        Long firstAuditTime = complaintReport.getFirstAuditTime().getTime();
        Long subTime;
        if (complaintReport.getReportStatus().equals(Constants.COMPLETE)) {
            completeCount += 1;
            subTime = complaintReport.getCompleteTime().getTime();
        } else {
            notCompleteCount += 1;
            if (null == complaintReport.getSolutionTime()) {
                subTime = System.currentTimeMillis();
            } else {
                subTime = complaintReport.getSolutionTime().getTime();
            }
        }
        Integer size = getComplaintLogStatus(complaintReport.getId(), null, "中断处理");
        if (size > 0) {
            stopCount += 1;
        }
        if (complaintReport.isTimeOut()) {
            timeOut += 1;
        }
        double actualTime = subTime - firstAuditTime;
        totalTime += Double.valueOf(getDecimalDouble(actualTime / 1000 / 60 / 60));
    }


    private Integer getComplaintLogStatus(Long complaintId, Long userId, String status) {
        QComplaintReportLog qComplaintReportLog = QComplaintReportLog.complaintReportLog;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qComplaintReportLog.deleted.eq(false));
        builder.and(qComplaintReportLog.enabled.eq(true));
        if (null != userId) {
            builder.and(qComplaintReportLog.user.id.eq(userId));
        }
        builder.and(qComplaintReportLog.complaintReportId.eq(complaintId));
        if (!StringUtils.isEmpty(status)) {
            builder.and(qComplaintReportLog.reportStatus.like("%" + status + "%"));
        }
        List<ComplaintReportLog> complaintReportLogList = (List<ComplaintReportLog>) complaintReportLogRepository.findAll(builder);
        return complaintReportLogList.size();
    }

    private static String getDecimalDouble(Double doubleValue) {
        DecimalFormat df = new DecimalFormat("####0.0");
        return df.format(doubleValue);
    }


    /**
     * 统计第二张表
     *
     * @param complaintReport
     */
    private void reportProvinceMap(ComplaintReport complaintReport) {
        ComplaintReportData data = complaintReportDataRepository.selectByQuestion(complaintReport.getId(), 189L);
        if (null != data) {
            //统计每个省份所用的时间
            Long firstAuditTime = complaintReport.getFirstAuditTime().getTime();
            Long subTime = 0L;
            if (complaintReport.getReportStatus().equals(Constants.COMPLETE)) {
                subTime = complaintReport.getCompleteTime().getTime();
            } else {
                if (null == complaintReport.getSolutionTime()) {
                    subTime = System.currentTimeMillis();
                } else {
                    subTime = complaintReport.getSolutionTime().getTime();
                }
            }
            double actualTime = (subTime - firstAuditTime);
            actualTime = actualTime / 1000 / 60 / 60;
            //统计每个省份的次数
            if (reportProvinceMap.containsKey(data.getAnswerOther())) {
                String[] array = reportProvinceMap.get(data.getAnswerOther());
                Integer count = Integer.valueOf(array[0]) + 1;
                double time = Double.valueOf(array[1]) + Double.valueOf(getDecimalDouble(actualTime));

                String[] provinceTimeArray = new String[2];
                provinceTimeArray[0] = count.toString();
                provinceTimeArray[1] = getDecimalDouble(time);

                reportProvinceMap.put(data.getAnswerOther(), provinceTimeArray);
            } else {
                String[] provinceTimeArray = new String[2];
                provinceTimeArray[0] = String.valueOf(1);
                provinceTimeArray[1] = getDecimalDouble(actualTime);
                reportProvinceMap.put(data.getAnswerOther(), provinceTimeArray);
            }
        }
    }


    /**
     * 统计第三张表
     *
     * @param complaintReport
     */
    private void reportBrandMap(ComplaintReport complaintReport) {
        ComplaintReportData data = complaintReportDataRepository.selectByQuestion(complaintReport.getId(), 194L);
        if (null != data) {
            if (StringUtils.isNotEmpty(data.getAnswerOther())) {
                if (reportOtherBrandMap.containsKey(data.getAnswerOther())) {
                    Integer value = reportOtherBrandMap.get(data.getAnswerOther());
                    reportOtherBrandMap.put(data.getAnswerOther(), value + 1);
                } else {
                    reportOtherBrandMap.put(data.getAnswerOther(), 1);
                }
            }
            if (StringUtils.isNotEmpty(data.getAnswerId())) {
                for (String brandId : data.getAnswerId().split(",")) {
                    if (brandId.equals("447")) {
                        continue;
                    }
                    QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(brandId));
                    if (null != answerOption && StringUtils.isNotEmpty(answerOption.getName())) {
                        if (reportBrandMap.containsKey(answerOption.getName())) {
                            Integer value = reportBrandMap.get(answerOption.getName());
                            reportBrandMap.put(answerOption.getName(), value + 1);
                        } else {
                            reportBrandMap.put(answerOption.getName(), 1);
                        }
                    }
                }
            }
        }
    }


    /**
     * 统计第五张表
     */
    private void reportUserMap(ComplaintReport complaintReport) {
        if (complaintReport.isLeaderFollow()) {
            leaderFollowConut += 1;
        }
        BooleanBuilder builder = new BooleanBuilder();
        QComplaintReportLog qComplaintReportLog = QComplaintReportLog.complaintReportLog;
        builder.and(qComplaintReportLog.deleted.eq(false));
        builder.and(qComplaintReportLog.enabled.eq(true));
        builder.and(qComplaintReportLog.orange.eq(true));
        builder.and(qComplaintReportLog.complaintReportId.eq(complaintReport.getId()));
        List<ComplaintReportLog> list = (List<ComplaintReportLog>) complaintReportLogRepository.findAll(builder);
        if (list.isEmpty()) {
            reasonableCount += 1;
        }
    }


    /**
     * 统计第六张表
     *
     * @param complaintReport
     */
    private void reportSolutionMap(ComplaintReport complaintReport) {
        ComplaintReportData data = complaintReportDataRepository.selectByQuestion(complaintReport.getId(), 195L);
        if (null != data) {
            if (StringUtils.isNotEmpty(data.getAnswerId())) {
                for (String id : data.getAnswerId().split(",")) {
                    QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                    if (null != answerOption && StringUtils.isNotEmpty(answerOption.getName())) {
                        if (reportSolutionMap.containsKey(answerOption.getName())) {
                            Integer value = reportSolutionMap.get(answerOption.getName());
                            reportSolutionMap.put(answerOption.getName(), value + 1);
                        } else {
                            reportSolutionMap.put(answerOption.getName(), 1);
                        }
                    }
                }
            }
        }
    }


    /**
     * 统计第七张表
     *
     * @param complaintReportId
     * @param userName
     */
    private void reportUserNameMap(List<Long> complaintReportId, String userName) {
        QUserProfile qUserProfile = QUserProfile.userProfile;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qUserProfile.deleted.eq(false));
        builder.and(qUserProfile.enabled.eq(true));
        builder.and(qUserProfile.realName.like("%" + userName + "%"));
        List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(builder);
        List<Long> userListId = new ArrayList<>();
        for (UserProfile userProfile : userProfileList) {
            userListId.add(userProfile.getUser().getId());
        }

        QComplaintUser qComplaintUser = QComplaintUser.complaintUser;
        builder = new BooleanBuilder();
        builder.and(qComplaintUser.deleted.eq(false));
        builder.and(qComplaintUser.enabled.eq(true));
        builder.and(qComplaintUser.user.id.in(userListId));
        builder.and(qComplaintUser.complaintReport.id.in(complaintReportId));
        List<ComplaintUser> complaintUserList = (List<ComplaintUser>) complaintUserRepository.findAll(builder);

        for (ComplaintUser complaintUser : complaintUserList) {
            UserProfile userProfile = userProfileRepository.findByUserId(complaintUser.getUser().getId());
            reportUserNameMap(complaintUser, userProfile);
        }
    }


    private void reportUserNameMap(ComplaintUser complaintUser, UserProfile userProfile) {
//        QComplaintUser qComplaintUser = QComplaintUser.complaintUser;
//        BooleanBuilder builder = new BooleanBuilder();
//        builder.and(qComplaintUser.deleted.eq(false));
//        builder.and(qComplaintUser.enabled.eq(true));
//        builder.and(qComplaintUser.complaintReport.id.eq(complaintUser.getComplaintReport().getId()));
//        builder.and(qComplaintUser.timeOut.eq(true));
//        builder.and(qComplaintUser.user.id.eq(userProfile.getUser().getId()));
//        List<ComplaintUser> logList = (List<ComplaintUser>) complaintUserRepository.findAll(builder);

        if (null != userProfile && StringUtils.isNotEmpty(userProfile.getRealName())) {
            if (reportUserNameMap.containsKey(userProfile.getId())) {
                String[] valueMap = reportUserNameMap.get(userProfile.getId());
                valueMap[1] = String.valueOf(Integer.valueOf(valueMap[1]) + 1);
                ComplaintReportData data = complaintReportDataRepository.selectByQuestion(complaintUser.getComplaintReport().getId(), 194L);
                if (null != data && StringUtils.isNotEmpty(data.getAnswerId())) {
                    Integer brandSize = data.getAnswerId().split(",").length;
                    valueMap[2] = String.valueOf(Integer.valueOf(valueMap[2]) + brandSize);
                }
                Integer complete = getComplaintLogStatus(complaintUser.getComplaintReport().getId(), userProfile.getUser().getId(), "已完成");
                if (complete > 0) {
                    valueMap[3] = String.valueOf(Integer.valueOf(valueMap[3]) + complete);
                } else {
                    ComplaintReport complaintReport = complaintUser.getComplaintReport();
                    if (null != complaintReport.getFollowUser()) {
                        if (userProfile.getUser().getId().equals(complaintReport.getFollowUser().getId())) {
                            if (complaintReport.getReportStatus().equals(Constants.BEGIN) || complaintReport.getReportStatus().equals(Constants.FOLLOW)) {
                                valueMap[4] = String.valueOf(Integer.valueOf(valueMap[4]) + 1);
                            }
                        }
                    }

                }
                complete = getComplaintLogStatus(complaintUser.getComplaintReport().getId(), userProfile.getUser().getId(), "中断处理");
                valueMap[5] = String.valueOf(Integer.valueOf(valueMap[5]) + complete);
                complete = getComplaintLogStatus(complaintUser.getComplaintReport().getId(), userProfile.getUser().getId(), "超时");
                valueMap[6] = String.valueOf(Integer.valueOf(valueMap[6]) + complete);
                reportUserNameMap.put(userProfile.getId(), valueMap);
            } else {
                String[] valueMap = new String[7];
                valueMap[0] = userProfile.getRealName();
                valueMap[1] = "1";
                valueMap[2] = "0";
                valueMap[3] = "0";
                valueMap[4] = "0";
                valueMap[5] = "0";
                valueMap[6] = "0";
                ComplaintReportData data = complaintReportDataRepository.selectByQuestion(complaintUser.getComplaintReport().getId(), 194L);
                if (null != data && StringUtils.isNotEmpty(data.getAnswerId())) {
                    Integer brandSize = data.getAnswerId().split(",").length;
                    valueMap[2] = brandSize.toString();
                }
                Integer complete = getComplaintLogStatus(complaintUser.getComplaintReport().getId(), userProfile.getUser().getId(), "已完成");
                if (complete > 0) {
                    valueMap[3] = complete.toString();
                } else {
                    ComplaintReport complaintReport = complaintUser.getComplaintReport();
                    if (null != complaintReport.getFollowUser()) {
                        if (userProfile.getUser().getId().equals(complaintReport.getFollowUser().getId())) {
                            if (complaintReport.getReportStatus().equals(Constants.BEGIN) || complaintReport.getReportStatus().equals(Constants.FOLLOW)) {
                                valueMap[4] = "1";
                            }
                        }
                    }
                }
                valueMap[5] = getComplaintLogStatus(complaintUser.getComplaintReport().getId(), userProfile.getUser().getId(), "中断处理").toString();
                valueMap[6] = getComplaintLogStatus(complaintUser.getComplaintReport().getId(), userProfile.getUser().getId(), "超时").toString();
                reportUserNameMap.put(userProfile.getId(), valueMap);
            }
        }
    }


}
